import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_demo/bean/home_module.dart';
import 'package:flutter_demo/mixin/base_page.dart';
import 'package:flutter_demo/model/local/modules.dart';
import 'package:flutter_demo/widgets/app_widgets.dart';

import '../conf/m3.dart';
import '../generated/l10n.dart';

///首页
class HomePage extends StatelessWidget with BasePage {
  HomePage({super.key});

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    //Bloc是一个状态管理库，这里在首页注入提供者，为子组件（body、drawer）提供模块状态状态的查询与订阅
    return MultiBlocProvider(
      providers: [BlocProvider(create: (context) => HomeModulesCubit(context))],
      child: Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          centerTitle: true,
          title: BlocBuilder<HomeModulesCubit, HomeModulesState>(
            builder: (c, s) => Text(s.getSelectedModuleInfo()?.title ?? ""),
          ),
        ),
        body: _MainContent(),
        drawer: _MainDrawer(),
        drawerEnableOpenDragGesture: true,
        drawerEdgeDragWidth: double.infinity,
        // drawerScrimColor: Colors.transparent,
      ),
    );
  }
}

///Drawer
class _MainDrawer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    HomeModulesCubit homeModulesCubit = BlocProvider.of(context);
    return Drawer(
      child: SafeArea(
        child: Column(
          children: [
            Container(
              height: 60,
              alignment: Alignment.center,
              child: Text(
                S.of(context).module_list_title,
                style: const TextStyle(fontSize: 20),
              ),
            ),
            //使用Expanded使ListView可以固定高度，否则Column会变成无限高，而ListView始终无
            // 法确认自己的高度导致报错
            Expanded(
              child: BlocBuilder<HomeModulesCubit, HomeModulesState>(
                buildWhen: (s1, s2) => s2 is OnModuleListUpdate,
                builder: (c, s) => PagePadding(
                  ListView.builder(
                    itemCount: s.moduleList.length,
                    itemBuilder: (c, i) {
                      return BlocBuilder<HomeModulesCubit, HomeModulesState>(
                        buildWhen: (s1, s2) =>
                            s2 is OnSelectedIndexUpdate &&
                            (s1.selectedIndex == i || s2.selectedIndex == i),
                        builder: (c, s) => Ink(
                          decoration: BoxDecoration(
                            color: s.selectedIndex == i
                                ? Theme.of(context).colorScheme.primaryContainer
                                : Colors.transparent,
                            borderRadius: BorderRadius.circular(30),
                          ),
                          child: InkWell(
                            borderRadius: BorderRadius.circular(30),
                            onTap: () {
                              homeModulesCubit.updateSelectedIndex(i);
                              Navigator.of(context).maybePop();
                            },
                            child: Container(
                              width: double.infinity,
                              height: 60,
                              padding: const EdgeInsetsDirectional.symmetric(
                                  horizontal: 30, vertical: M3.paddingS),
                              alignment: AlignmentDirectional.centerStart,
                              child: Text(
                                s.moduleList[i].title,
                                style: TextStyle(
                                    color: s.selectedIndex == i
                                        ? Theme.of(context)
                                            .colorScheme
                                            .onPrimaryContainer
                                        : Theme.of(context)
                                            .colorScheme
                                            .onSurface),
                              ),
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// 首页展示当前选中模块的页面列表
class _MainContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return PagePadding(
      BlocBuilder<HomeModulesCubit, HomeModulesState>(
        builder: (c, s) {
          return LayoutBuilder(
            builder: (context, constraints) {
              return ListView.builder(
                itemCount: s.getSelectedModuleInfo()?.pages.length ?? 0,
                itemBuilder: (c, i) {
                  final data = s.getSelectedModuleInfo()?.pages[i];
                  if (data is PageInfo) {
                    return _buildPageItem(c, constraints, data);
                  } else {
                    return PrimaryTitle(data.toString());
                  }
                },
              );
            },
          );
        },
      ),
    );
  }

  Widget _buildPageItem(
    BuildContext context,
    BoxConstraints constraints,
    PageInfo? pageInfo,
  ) {
    return Row(
      children: [
        Container(
          constraints: BoxConstraints(
            //这里为了item能自适应内容宽度，采用Row包裹让它的宽度不受ListView
            // 强制填满父组件的影响，但会导致内容溢出显示范围，这里加个约束，让
            // item宽度不超出List,
            //通过LayoutBuilder使得widget在布局阶段才构建，这样可以得到父组
            // 件的约束
            maxWidth: constraints.maxWidth,
            //通过MediaQuery也可以查询到设备参数，并在参数改变时重建组件，但它
            // 的性能比不上LayoutBuilder
            // maxWidth: MediaQuery.sizeOf(c).width - M3.paddingL * 2,
          ),
          margin:
              const EdgeInsetsDirectional.symmetric(vertical: M3.paddingM / 2),
          child: Ink(
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.surfaceContainer,
              borderRadius: BorderRadius.circular(20),
            ),
            child: InkWell(
              borderRadius: BorderRadius.circular(20),
              onTap: () => pageInfo?.jumpPage(context),
              child: Container(
                padding: const EdgeInsetsDirectional.symmetric(
                    horizontal: M3.paddingL, vertical: M3.paddingS),
                child: Text(
                  pageInfo?.title ?? "",
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Theme.of(context).colorScheme.onSurfaceVariant),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}
